# -*- mode: python -*-

import os
from qutebrowser.config.configfiles import ConfigAPI  # noqa: F401
from qutebrowser.config.config import ConfigContainer  # noqa: F401
from enum import Enum

config = config  # type: ConfigAPI # noqa: F821
c = c  # type: ConfigContainer # noqa: F821

initial_start = c.tabs.background == False

if initial_start:
    # ui
    c.completion.scrollbar.width = 10
    c.tabs.position = 'top'
    c.tabs.show = 'multiple'
    c.tabs.favicons.show = False
    c.tabs.indicator.width = 0
    c.tabs.title.format = '{title}'
    c.tabs.title.alignment = 'center'
    c.downloads.position = 'bottom'
    c.tabs.favicons.show = False

    # behavior
    c.downloads.location.prompt = False
    c.hints.scatter = False
    c.url.searchengines = {'DEFAULT': 'https://google.com/search?q={}' }
    c.input.insert_mode.auto_load = True
    c.input.insert_mode.auto_leave = False
    c.tabs.background = True
    c.editor.command = [ os.environ['EDITOR'] + ' "{}"' ]
    c.auto_save.session = True

    # binds
    config.bind('<Shift-i>', 'config-source')


# mustache templated from current theme
theme = {
    'panel': {
        'height': {{p_height}},
    },

    'fonts': {
        'tabbar': '{{q_tab_font}}',
        'completion': '{{q_tab_font}}',
        'completion_size': {{q_tab_fontsize_small}},
        'tab_bold': {{q_tab_bold}},
        'tab_size': {{q_tab_fontsize}},
        'status_size': {{q_tab_fontsize_small}},
    },

    'colors': {
        'bg': {
            'normal': '#{{p_bg_normal}}',
            'active': '#{{p_bg_active}}',
            'inactive': '#{{p_bg_inactive}}',
        },

        'fg': {
            'normal': '#{{p_fg_normal}}',
            'active': '#{{p_fg_active}}',
            'inactive': '#{{p_fg_inactive}}',
            'match': '#{{p_icon}}', # completion and hints
        },
    }
}

# colors
colors = theme['colors']

def setToBG(colortype, target):
    config.set('colors.' + target, colors['bg'][colortype])

def setToFG(colortype, target):
    config.set('colors.' + target, colors['fg'][colortype])

def colorSync(colortype, setting):
    if setting.endswith('.fg'):
        setToFG(colortype, setting)
    elif setting.endswith('.bg'):
        setToBG(colortype, setting)
    elif setting.endswith('.top') or setting.endswith('.bottom'):
        setToFG(colortype, setting)
    else:
        setToFG(colortype, setting + '.fg')
        setToBG(colortype, setting + '.bg')

targets = {
    'normal' : [
        'statusbar.normal',
        'statusbar.command',
        'statusbar.url.success.http.fg',
        'statusbar.url.success.https.fg',
        'hints',
        'downloads.bar.bg',
        'completion.category',

        'tabs.even',
        'tabs.odd',
    ],

    'active' : [
        'tabs.selected.even',
        'tabs.selected.odd',
        'statusbar.insert',
        'downloads.stop',
        'prompts',
        'messages.warning',
        'messages.error',
        'statusbar.url.hover.fg',
        'completion.item.selected',

        'completion.category.border.top',
        'completion.category.border.bottom',

        'completion.item.selected.border.top',
        'completion.item.selected.border.bottom',
    ],

    'inactive' : [
        'completion.scrollbar',
        'downloads.start',
        'messages.info',
        'completion.fg',
        'completion.odd.bg',
        'completion.even.bg',
    ],

    'match' : [
        'completion.match.fg',
        'hints.match.fg',
    ]
}

for colortype in targets:
    for target in targets[colortype]:
        colorSync(colortype, target)

setToFG('active', 'statusbar.progress.bg')

config.set('hints.border', '1px solid ' + colors['fg']['normal'])

# tabbar
def makePadding(top, bottom, left, right):
    return { 'top': top, 'bottom': bottom, 'left': left , 'right': right }

# TODO improve this logic

# assume height of font is ~10px, pad top by half match panel height
# txth reference
# ./txth -f "xft:${font_name}:style=Regular" -s $font_size "asdf"

surround = round((theme['panel']['height'] - 10) / 2)
c.tabs.padding = makePadding(surround, surround, 8, 8)
c.tabs.indicator.padding = makePadding(0, 0, 0, 0)

# fonts
fonts = theme['fonts']
c.fonts.monospace = fonts['tabbar']

def GetSize(fontType):
    return str(fonts[fontType + '_size']) + 'pt '

tabFont = GetSize('tab') + fonts['tabbar']

if fonts['tab_bold']:
   tabFont = 'bold {0}'.format(tabFont)

c.fonts.tabs = tabFont
c.fonts.completion.entry = GetSize('completion') + fonts['completion']

# userscripts
# this allows some extra control across platforms, like wrapping bash scripts on windows 
userscripts = [
    {
        'name': 'update_tp',
        'bind': 'su',
        'script':
        """
        notify-send "$QUTE_URL"
        echo "$QUTE_URL" > ~/.qute_url
        emacsclient --eval "(progn (tp-update-git-message))"
        """
    }
]

userscript_location = os.environ['HOME'] + "/.local/share/qutebrowser/userscripts/"
if os.name == 'nt':
    userscript_location = os.environ['APPDATA'] + '\\qutebrowser\\data\\userscripts\\';

def write_file(file, content):
        with open(file, 'w') as fh:
            fh.write(content)

def write_userscript(location, content):
    write_file(location, content)

    if os.name == 'nt':
        location = location + '_wrapped.bat'
        write_file(location, '"C:\\Program Files\\Git\\bin\\sh" "' + location + '"')

    return os.path.basename(location)

for userscript in userscripts:
    script_file = userscript_location + userscript['name']
    if not os.path.isfile(script_file):
        bindname = write_userscript(script_file, userscript['script'])
        config.bind(userscript['bind'], 'spawn --userscript ' + bindname)
